﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using CommonLib;

[RequireComponent(typeof(Collider2D))]
[RequireComponent(typeof(Rigidbody2D))]
public class RoleCtrl : MonoBehaviour
{
	[SerializeField]
	protected Rigidbody2D rb2d;
	[SerializeField]
	protected InputControl input;
	[SerializeField]
	protected Animator animator;

	public MoveCtrl2D SubManagerMove { get; protected set; }
	public RoleAtrEntity RoleEntity { get; protected set; }


	#region LifeTimecircle
	virtual protected void Update()
	{
		SubManagerMove.Update();
		RoleEntity.UpdateFactor(Time.deltaTime);	
		//animator.SetFloat("Horizontal", horizenInput);
		//animator.SetFloat("Vertical", verticalInput);
	}
	virtual protected void FixedUpdate()
	{
		SubManagerMove.FixedUpdate();
	}
	virtual protected void OnCollisionEnter2D(Collision2D collision)
	{
		if (collision.gameObject.tag == "Player")
		{
			RoleCtrl other = collision.gameObject.GetComponent<RoleCtrl>();
			if (this.RoleEntity.CurrentScore < other.RoleEntity.CurrentScore)
			{
				Debug.Log($"死亡 {this.gameObject.name}");
				this.PlayerDie();
			}
		}
	}
	#endregion

	#region Role状态触发
	/// <summary>
	/// 操作单位初始 
	/// </summary>
	public void PlayerInit()
	{
		RA_OnInit?.Invoke(this);
		OnInit();
	}
	/// <summary>
	/// 需要重写实现的具体初始化操作
	/// </summary>
	virtual protected void OnInit()
	{
		SubManagerMove = new MoveCtrl2D(this, rb2d);
		RoleEntity = new RoleAtrEntity(roleObject);
	}
	/// <summary>
	/// 操作单位死亡
	/// </summary>
	public void PlayerDie()
	{
		RA_OnDie?.Invoke(this);
		//处理控制角色死亡时的操作
		OnDie();
	}
	/// <summary>
	/// 需要重写实现的具体死亡操作
	/// </summary>
	virtual protected void OnDie(){
		//Left Over: 将Entity进行回收 进入pool中 在OnDie中执行
		//Destroy(this.gameObject);
		//TODO Clear Event
		RA_OnDie = null;
	}
	#endregion


	#region 调用
	public void BiuldRole(RoleAtrEntity role) {
		RoleEntity = role;
		PlayerInit();
	}

	public void UseSkill(Skill skill)
	{
		if (RoleEntity.CheckSkillVaild(skill))
		{
			skill.Execute(this);
			RoleEntity.RemoveSkill(skill);
		}
	}
	public void AddSkill(Skill skill)
	{
		RoleEntity.AddSkill(skill);
	}
	public void RemoveSkill(Skill skill)
	{
		RoleEntity.RemoveSkill(skill);
	}

	#endregion

	private void Awake()
	{
		PlayerInit();
	}




	[SerializeField]
	ScriptObjectRole roleObject = null;
	#region 时点触发事件定义
	public delegate void RoleAction(RoleCtrl ctrl);
	public RoleAction RA_OnDie;
	public RoleAction RA_OnInit;
	#endregion
}